package org.hgvc.webapp.ets.spring.service;

import java.util.Date;
import java.util.List;

import org.hgvc.webapp.ets.bo.ActionBulletin;
import org.hgvc.webapp.ets.constant.ActionBulletinConstant;
import org.hgvc.webapp.ets.constant.SystemConstant;
import org.hgvc.webapp.ets.spring.dao.SystemHbmDao;
import org.jocsb.base.bo.Role;
import org.jocsb.base.bo.User;
import org.jocsb.base.exception.BaseException;
import org.jocsb.base.util.BeanUtil;
import org.jocsb.base.util.SpringUtils;


public class SystemServiceImpl implements SystemService {

	private SystemHbmDao dao;

	public SystemHbmDao getDao() {
		return dao;
	}

	public void setDao(SystemHbmDao dao) {
		this.dao = dao;
	}
	
	public List<ActionBulletin> getActionBulletinList(String userId)throws BaseException{
		try{
			return dao.getActionBulletinListByUserId(userId);
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.list.action.bulletin", new Object[]{}));
		}
	}
	
	public void deleteActionBulletinByActionNo(String actionNo)throws BaseException{
		try{
			dao.deleteActionBulletinByActionNo(actionNo);
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.delete.action.bulletin", new Object[]{}));
		}
	}
	
	public void ackActionBulletin(ActionBulletin ab,User ackUser)throws BaseException{
		try{
			
			ActionBulletin newAb = new ActionBulletin();
			BeanUtil.copyFields(ab, newAb, true);
			
			newAb.setModifiedBy(null);
			newAb.setModifiedDate(null);
			newAb.setUser(ackUser);
			newAb.setAckUser(ackUser);
			newAb.setActionBulletinId(null);
			newAb.setCreatedDate(new Date());
			newAb.setCreatedBy(SystemConstant.SYSTEM_USER);
			newAb.setType(ActionBulletinConstant.AB_ACTION_TYPE);
			//delete 
			dao.deleteActionBulletinByActionNo(newAb.getActionNo());
			
			dao.save(newAb);
			
			
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.ack.action.bulletin", new Object[]{}));
		}
	}
	
	public void createActionBulletinByRoles(ActionBulletin ab,Role role)throws BaseException{
		try{
			List<User> usrs = dao.getUsersByRole(role.getRoleId());
			for(User usr:usrs){
				ActionBulletin newAB = new ActionBulletin();
				BeanUtil.copyFields(ab, newAB, true);
				newAB.setUser(usr);
				dao.save(newAB);
			}
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.invoke.method", new Object[]{"createActionBulletinByRoles()"}));
			
		}
		
	}
	
	public void createActionBulletinByUser(ActionBulletin ab,User usr)throws Exception{
			ab.setUser(usr);
			dao.save(ab);
	}
	
}
